import { createModuleLogger } from '@/utils/logger';
import { PrismaService } from '@/services/database/PrismaService';
import { PriceService } from '@/services/price/PriceService';
import MonitoringManager from '@/services/blockchain/MonitoringManager';
import { broadcastSSE } from '@/app/api/sse/route';

const logger = createModuleLogger('monitoring-lite-init');

// 验证数据库表的完整性
async function validateDatabaseTables(prismaService: PrismaService): Promise<void> {
  try {
    // 检查链配置表
    const chainConfigCount = await prismaService.getClient().chainMonitorConfig.count();
    logger.info(`📊 链配置表记录数: ${chainConfigCount}`);
    
    if (chainConfigCount === 0) {
      logger.warn('⚠️ 链配置表为空，建议运行: node scripts/init-chain-configs.js');
    }
    
    // 检查监控代币表
    const tokenCount = await prismaService.getClient().monitoredToken.count();
    logger.info(`📊 监控代币表记录数: ${tokenCount}`);
    
    if (tokenCount === 0) {
      logger.warn('⚠️ 监控代币表为空，建议运行: node scripts/init-top1000-tokens.js');
    }
    
    // 检查活跃代币数量
    const activeTokenCount = await prismaService.getClient().monitoredToken.count({
      where: { isActive: true }
    });
    
    if (activeTokenCount < 10) {
      logger.warn(`⚠️ 活跃监控代币较少 (${activeTokenCount})，可能影响价格监控效果`);
    }
    
  } catch (error) {
    logger.warn('数据库表检查失败，可能需要运行数据库迁移:', error);
    throw new Error(`Database tables validation failed: ${error instanceof Error ? error.message : String(error)}. Please run: npm run db:migrate`);
  }
}

// 使用全局对象保存服务实例，避免在Next.js开发模式下被重置
const globalForServices = globalThis as unknown as {
  prismaService: PrismaService | null | undefined;
  priceService: PriceService | null | undefined;
  monitoringManager: MonitoringManager | null | undefined;
  isLiteInitialized: boolean | undefined;
  retryIntervalId: NodeJS.Timeout | null | undefined; // 添加定时器ID管理
};

// 轻量级监控所需的服务
let prismaService = globalForServices.prismaService || null;
let priceService = globalForServices.priceService || null;
let monitoringManager = globalForServices.monitoringManager || null;
let isLiteInitialized = globalForServices.isLiteInitialized || false;
let retryIntervalId = globalForServices.retryIntervalId || null;

// 同步到全局对象的函数
function syncToGlobal() {
  globalForServices.prismaService = prismaService;
  globalForServices.priceService = priceService;
  globalForServices.monitoringManager = monitoringManager;
  globalForServices.isLiteInitialized = isLiteInitialized;
  globalForServices.retryIntervalId = retryIntervalId;
}

/**
 * 轻量级监控初始化 - 只初始化链监控必需的服务
 */
export async function initializeLiteMonitoring(): Promise<{
  prisma: PrismaService;
  price: PriceService;
  monitoring: MonitoringManager;
}> {
  if (isLiteInitialized && prismaService && priceService && monitoringManager) {
    // 检查数据库连接状态
    try {
      await prismaService.getClient().$queryRaw`SELECT 1`;
      logger.info('✅ 轻量级监控服务已初始化');
      return {
        prisma: prismaService,
        price: priceService,
        monitoring: monitoringManager
      };
    } catch (error) {
      logger.warn('⚠️ 数据库连接已断开，重新初始化...');
      prismaService = null;
      isLiteInitialized = false;
      syncToGlobal();
    }
  }

  try {
    logger.info('🚀 初始化轻量级监控服务...');

    // 1. 初始化数据库服务
    if (!prismaService) {
      try {
        prismaService = new PrismaService();
        await prismaService.connect();
        
        // 检查关键表是否存在和有数据
        await validateDatabaseTables(prismaService);
        
        logger.info('✅ 数据库服务已初始化');
      } catch (error) {
        prismaService = null; // 连接失败时重置为null
        syncToGlobal();
        throw error;
      }
    }

    // 2. 初始化价格服务  
    if (!priceService) {
      priceService = PriceService.getInstance();
      await priceService.initialize();
      logger.info('✅ 价格服务已初始化');
    }

    // 3. 初始化监控管理器
    if (!monitoringManager) {
      monitoringManager = MonitoringManager.getInstance();
      
      // 设置交易回调用于数据库保存和实时广播
      monitoringManager.addTransactionCallback(async (transaction: any) => {
        try {
          // 保存交易到数据库 - 添加await确保正确等待
          if (transaction && prismaService) {
            await prismaService.saveTransaction(transaction);
          }

          // 实时广播
          broadcastSSE({
            type: 'transaction',
            data: transaction
          });
        } catch (error) {
          logger.error('交易处理失败:', error);
        }
      });
      
      // 设置定期重试降级存储的交易 (每5分钟执行一次)
      // 避免重复创建定时器
      if (!retryIntervalId) {
        retryIntervalId = setInterval(async () => {
          if (prismaService) {
            try {
              await prismaService.retryFallbackTransactions();
            } catch (error) {
              logger.error('重试降级交易失败:', error);
            }
          }
        }, 5 * 60 * 1000); // 5分钟
        
        logger.info('✅ 定期重试机制已启动 (5分钟间隔)');
      } else {
        logger.debug('⏭️ 定期重试机制已存在，跳过创建');
      }
      
      logger.info('✅ 监控管理器已初始化');
    }

    isLiteInitialized = true;
    syncToGlobal(); // 同步状态到全局对象
    logger.info('🎉 轻量级监控服务初始化完成！');

    return {
      prisma: prismaService,
      price: priceService,
      monitoring: monitoringManager
    };

  } catch (error) {
    logger.error('❌ 轻量级监控服务初始化失败:', error);
    throw error;
  }
}

/**
 * 启动监控（轻量级）
 */
export async function startLiteMonitoring(): Promise<{
  success: boolean;
  message: string;
  activeCount: number;
  status: any;
  error?: string;
}> {
  try {
    // 初始化必需服务
    const { monitoring } = await initializeLiteMonitoring();
    
    // 检查是否已经启动 - 只计算健康的监控器
    const currentStatus = monitoring.getAllStatus();
    const healthyMonitors = Object.values(currentStatus.chains).filter(
      (chain: any) => chain.isActive && chain.status === 'running'
    ).length;

    if (healthyMonitors > 0) {
      return {
        success: true,
        message: `监控服务已经在运行中 (健康监控器: ${healthyMonitors} 个)`,
        activeCount: healthyMonitors,
        status: currentStatus
      };
    }

    // 启动所有已启用的监控器
    logger.info('🚀 启动区块链监控...');
    await monitoring.startAllMonitors();
    
    const finalStatus = monitoring.getAllStatus();
    const finalHealthyCount = Object.values(finalStatus.chains).filter(
      (chain: any) => chain.isActive && chain.status === 'running'
    ).length;
    
    logger.info(`✅ 监控启动完成: 健康监控器 ${finalHealthyCount} 个`);
    
    // 如果没有健康的监控器，应该返回失败
    if (finalHealthyCount === 0) {
      return {
        success: false,
        message: 'Monitor startup completed but no healthy monitors are running. Check logs and database configuration.',
        activeCount: 0,
        status: finalStatus,
        error: 'No healthy monitors started'
      };
    }
    
    return {
      success: true,
      message: `监控服务已启动，当前健康监控器: ${finalHealthyCount} 个`,
      activeCount: finalHealthyCount,
      status: finalStatus
    };
    
  } catch (error) {
    logger.error('❌ 启动监控失败:', error);
    return {
      success: false,
      message: '启动监控失败',
      activeCount: 0,
      status: { activeCount: 0, monitorCount: 0, chains: {} },
      error: error instanceof Error ? error.message : String(error)
    };
  }
}

/**
 * 停止监控（轻量级）
 */
export async function stopLiteMonitoring(): Promise<{
  success: boolean;
  message: string;
  error?: string;
}> {
  try {
    if (!monitoringManager) {
      return {
        success: true,
        message: '监控服务未运行'
      };
    }

    await monitoringManager.stopAllMonitors();
    logger.info('✅ 监控服务已停止');
    
    return {
      success: true,
      message: '监控服务已停止'
    };
    
  } catch (error) {
    logger.error('❌ 停止监控失败:', error);
    return {
      success: false,
      message: '停止监控失败',
      error: error instanceof Error ? error.message : String(error)
    };
  }
}

/**
 * 获取监控状态（轻量级）
 */
export function getLiteMonitoringStatus(): {
  initialized: boolean;
  monitoring: any | null;
} {
  return {
    initialized: isLiteInitialized,
    monitoring: monitoringManager?.getAllStatus() || null
  };
}

/**
 * 关闭轻量级监控服务
 */
export async function shutdownLiteMonitoring(): Promise<void> {
  try {
    if (monitoringManager) {
      await monitoringManager.stopAllMonitors();
    }
    
    if (prismaService) {
      await prismaService.disconnect();
    }
    
    // 清理定时器
    if (retryIntervalId) {
      clearInterval(retryIntervalId);
      retryIntervalId = null;
      logger.info('✅ 定期重试定时器已清理');
    }
    
    isLiteInitialized = false;
    prismaService = null;
    priceService = null;
    monitoringManager = null;
    
    syncToGlobal(); // 同步状态到全局对象
    logger.info('✅ 轻量级监控服务已关闭');
  } catch (error) {
    logger.error('❌ 关闭轻量级监控服务失败:', error);
  }
}

// 为了兼容现有API，添加别名函数
export const initializeServices = initializeLiteMonitoring;
export const startBlockchainMonitoring = startLiteMonitoring;
export const shutdownServices = shutdownLiteMonitoring;

/**
 * 检查服务是否已初始化
 */
export function isServicesInitialized(): boolean {
  return globalForServices.isLiteInitialized || false;
}

/**
 * 获取监控管理器实例
 */
export function getMonitoringManager(): MonitoringManager | null {
  return globalForServices.monitoringManager || null;
}

// 只在生产环境下自动初始化，开发环境通过API手动启动
if (typeof window === 'undefined') { // 服务端环境
  if (process.env.NODE_ENV === 'production') {
    console.log('🔧 生产环境：自动初始化基础服务...');
    initializeLiteMonitoring().then(() => {
      if (process.env.AUTO_START_MONITORING === 'true') {
        console.log('🔧 生产环境：自动启动监控...');
        
        // 添加重试机制
        const startWithRetry = async (retries = 3) => {
          for (let i = 0; i < retries; i++) {
            try {
              const result = await startLiteMonitoring();
              if (result.success && result.activeCount > 0) {
                console.log(`✅ 监控服务启动成功 (健康监控器: ${result.activeCount} 个)`);
                return;
              } else if (result.success && result.activeCount === 0) {
                console.warn('⚠️ 监控服务启动但没有活跃的监控器');
              } else {
                throw new Error(result.error || '启动失败但无具体错误信息');
              }
            } catch (error) {
              console.error(`启动尝试 ${i + 1}/${retries} 失败:`, error);
              if (i < retries - 1) {
                const delay = 5000 * (i + 1); // 递增延迟: 5s, 10s, 15s
                console.log(`等待 ${delay/1000}秒 后重试...`);
                await new Promise(resolve => setTimeout(resolve, delay));
              }
            }
          }
          console.error('❌ 监控服务启动最终失败，请检查配置和日志');
          // 可以在这里添加告警通知
        };
        
        startWithRetry().catch(console.error);
      } else {
        console.log('💡 AUTO_START_MONITORING未启用，等待手动启动');
      }
    }).catch((error) => {
      console.error('❌ 基础服务初始化失败:', error);
      // 可以在这里添加系统级告警
    });
  } else {
    console.log('🔧 开发环境：服务将通过API按需初始化');
    console.log('💡 使用 POST /api/admin/monitoring/start 启动监控');
  }
}

// Graceful shutdown on process termination
process.on('SIGTERM', async () => {
  logger.info('🛑 Received SIGTERM, shutting down gracefully...');
  await shutdownLiteMonitoring();
  process.exit(0);
});

process.on('SIGINT', async () => {
  logger.info('🛑 Received SIGINT, shutting down gracefully...');
  await shutdownLiteMonitoring();
  process.exit(0);
}); 